import { Component, Injector, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { FlowworkauditmodelComponent } from '../flowworkauditmodel/flowworkauditmodel.component';

import { WorkflowServiceProxy, UserServiceProxy, GetWorkflowInstanceViewDto, OutsourcingWorkFlowServiceProxy } from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import * as _ from 'lodash';
import * as moment from 'moment';
import { from } from 'rxjs';
import { AwaitQuotationFormComponent } from '../AwaitQuotationWorkFlow/AwaitQuotationForm/AwaitQuotationForm.component';
@Component({
  selector: 'app-AwaitQuotationWorkFlow',
  templateUrl: './AwaitQuotationWorkFlow.component.html',
  styleUrls: ['./AwaitQuotationWorkFlow.component.css']
})
export class AwaitQuotationWorkFlowComponent extends AppComponentBase {
  @ViewChild('awaitQuotationForm') awaitQuotationForm: AwaitQuotationFormComponent;
  @ViewChild('dataTable') dataTable: Table;
  @ViewChild('paginator') paginator: Paginator;

  filterText = '';
  getWorkflowInstanceViewDtos: GetWorkflowInstanceViewDto[];
  constructor(injector: Injector,
    private _outsourcingWrokFlowService: OutsourcingWorkFlowServiceProxy,
    private _workflowServiceProxy: WorkflowServiceProxy,
    private _userServiceProxy: UserServiceProxy) {
    super(injector);
  }

  ngOnInit() {
  }

  getBacklogWorkflow(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.paginator.changePage(0);
      return;
    }

    this.primengTableHelper.showLoadingIndicator();

    this._outsourcingWrokFlowService.getQuotationWorkFlow(
      this.primengTableHelper.getMaxResultCount(this.paginator, event),
      this.primengTableHelper.getSkipCount(this.paginator, event),
      this.filterText
    )
      .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
      .subscribe(result => {
        this.primengTableHelper.totalRecordsCount = result.totalCount;
        //this.primengTableHelper.records = result.items;
        this.getWorkflowInstanceViewDtos = result.items;

        this.primengTableHelper.hideLoadingIndicator();

        _.forEach(this.getWorkflowInstanceViewDtos, viewItem => {
          let currentD = this.getWorkflowInstanceViewDtos.find((element) => (element.id === viewItem.id));
          this._workflowServiceProxy.getExecutionPointer(viewItem.id)
            .subscribe(pointResult => {
              if (pointResult.length > 0) {
                currentD.currentStepId = pointResult[0].id;
                currentD.currentStepTime = pointResult[0].startTime;
                currentD.receivedStepTimeInterval = this.dateDifference(pointResult[0].startTime);
              }
              else {
                currentD.currentStepId = '-';
                currentD.currentStepTime = null;
                currentD.receivedStepTimeInterval = '-';
              }
            });

          this._workflowServiceProxy.getOpenUserActions(viewItem.id)
            .subscribe(actionResult => {
              console.info(actionResult);
              currentD.currentStepName = actionResult[0].prompt;
            });
          this._outsourcingWrokFlowService.getOutsourcingWorkFlow(viewItem.id)
            .subscribe(actionResult => {
              console.info(actionResult);
              currentD.applyCode = actionResult.workFlowDto.code;
            });
        });
      });
  }

  dateDifference(actualDate): string {
    // Calculate time between two dates:
    const date1 = actualDate; // the date you already commented/ posted
    const date2: any = new Date(); // today

    let r = {}; // object for clarity
    let message: string;

    const diffInSeconds = Math.abs(date2 - date1) / 1000;
    const days = Math.floor(diffInSeconds / 60 / 60 / 24);
    const hours = Math.floor(diffInSeconds / 60 / 60 % 24);
    const minutes = Math.floor(diffInSeconds / 60 % 60);
    const seconds = Math.floor(diffInSeconds % 60);
    const milliseconds = Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);

    const months = Math.floor(days / 31);
    const years = Math.floor(months / 12);

    // the below object is just optional
    // if you want to return an object instead of a message
    r = {
      years: years,
      months: months,
      days: days,
      hours: hours,
      minutes: minutes,
      seconds: seconds,
      milliseconds: milliseconds
    };

    // check if difference is in years or months
    if (years === 0 && months === 0) {
      // show in days if no years / months
      if (days > 0) {
        if (days === 1) {
          message = days + ' 天';
        } else { message = days + ' 天'; }
      } else if (hours > 0) {
        if (hours === 1) {
          message = hours + ' 小时';
        } else {
          message = hours + ' 小时';
        }
      } else {
        // show in minutes if no years / months / days
        if (minutes === 1) {
          message = minutes + ' 分钟';
        } else {
          message = minutes + ' 分钟';
        }
      }
    } else if (years === 0 && months > 0) {
      // show in months if no years
      if (months === 1) {
        message = months + ' 月';
      } else {
        message = months + ' 月';
      }
    } else if (years > 0) {
      // show in years if years exist
      if (years === 1) {
        message = years + ' 年';
      } else {
        message = years + ' 年';
      }
    }

    return message + ' 前';
    // this is the message a user see in the view
  }

  quotationworkflow(id) {
      this.awaitQuotationForm.show(id);
  }

}
